import React, { useState } from 'react';
import { Card, Table, Select, Form, Input, Button, Space, Tag, Modal, Radio, Switch, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import './index.less';

const { Option } = Select;
const { confirm } = Modal;

const ValidationRules: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  
  // 模拟数据
  const rulesData = [
    {
      key: '1',
      id: 'VR001',
      name: '患者姓名非空验证',
      field: 'patientName',
      dataType: '字符型',
      ruleType: '非空',
      condition: 'NOT NULL',
      target: '患者信息',
      status: true,
      level: 'error',
      createTime: '2023-08-10'
    },
    {
      key: '2',
      id: 'VR002',
      name: '身份证号格式验证',
      field: 'idNumber',
      dataType: '字符型',
      ruleType: '正则表达式',
      condition: '^\\d{17}[\\dXx]$',
      target: '患者信息',
      status: true,
      level: 'error',
      createTime: '2023-08-11'
    },
    {
      key: '3',
      id: 'VR003',
      name: '年龄范围验证',
      field: 'age',
      dataType: '数值型',
      ruleType: '范围',
      condition: '0 <= value <= 120',
      target: '患者信息',
      status: true,
      level: 'warning',
      createTime: '2023-08-12'
    },
    {
      key: '4',
      id: 'VR004',
      name: '诊断编码规范验证',
      field: 'diagnosisCode',
      dataType: '字符型',
      ruleType: '引用值',
      condition: 'IN ICD-10',
      target: '诊断信息',
      status: false,
      level: 'warning',
      createTime: '2023-08-15'
    },
    {
      key: '5',
      id: 'VR005',
      name: '医嘱时间合理性',
      field: 'orderTime',
      dataType: '日期时间型',
      ruleType: '逻辑',
      condition: 'orderTime <= executeTime',
      target: '医嘱信息',
      status: true,
      level: 'error',
      createTime: '2023-08-18'
    }
  ];
  
  // 表格列定义
  const columns = [
    {
      title: '规则ID',
      dataIndex: 'id',
      key: 'id',
      width: 100
    },
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
      width: 160
    },
    {
      title: '验证字段',
      dataIndex: 'field',
      key: 'field',
      width: 120
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      key: 'dataType',
      width: 100
    },
    {
      title: '规则类型',
      dataIndex: 'ruleType',
      key: 'ruleType',
      width: 120
    },
    {
      title: '验证条件',
      dataIndex: 'condition',
      key: 'condition',
      width: 160
    },
    {
      title: '目标数据集',
      dataIndex: 'target',
      key: 'target',
      width: 120
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => {
        const color = level === 'error' ? 'error' : 'warning';
        const text = level === 'error' ? '错误' : '警告';
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => <Switch checked={status} size="small" />
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 110
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showEditModal(record)}><EditOutlined /></a>
          <a onClick={() => showDeleteConfirm(record)}><DeleteOutlined /></a>
        </Space>
      )
    }
  ];
  
  // 显示编辑模态框
  const showEditModal = (record) => {
    form.setFieldsValue({
      name: record?.name || '',
      field: record?.field || '',
      dataType: record?.dataType || '字符型',
      ruleType: record?.ruleType || '非空',
      condition: record?.condition || '',
      target: record?.target || '',
      level: record?.level || 'error',
      status: record?.status || true
    });
    setVisible(true);
  };
  
  // 显示删除确认框
  const showDeleteConfirm = (record) => {
    confirm({
      title: '确定要删除此规则吗?',
      icon: <ExclamationCircleOutlined />,
      content: `规则ID: ${record.id}，规则名称: ${record.name}`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('删除规则', record.id);
        // 实际应用中需要调用删除API
      }
    });
  };
  
  // 处理表单提交
  const handleSubmit = (values) => {
    console.log('表单值:', values);
    // 实际应用中需要调用保存API
    setVisible(false);
    form.resetFields();
  };
  
  return (
    <div className="validation-rules-container">
      <Card bordered={false} title="数据效验规则">
        <Form layout="inline" className="search-form">
          <Form.Item label="规则ID">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="规则名称">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item label="目标数据集">
            <Select placeholder="请选择" style={{ width: 150 }}>
              <Option value="all">全部</Option>
              <Option value="patient">患者信息</Option>
              <Option value="diagnosis">诊断信息</Option>
              <Option value="order">医嘱信息</Option>
              <Option value="exam">检验检查</Option>
            </Select>
          </Form.Item>
          <Form.Item label="规则类型">
            <Select placeholder="请选择" style={{ width: 120 }}>
              <Option value="all">全部</Option>
              <Option value="notNull">非空</Option>
              <Option value="regex">正则表达式</Option>
              <Option value="range">范围</Option>
              <Option value="reference">引用值</Option>
              <Option value="logic">逻辑</Option>
            </Select>
          </Form.Item>
          <Form.Item label="状态">
            <Select placeholder="请选择" style={{ width: 100 }}>
              <Option value="all">全部</Option>
              <Option value="active">启用</Option>
              <Option value="inactive">停用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />}>搜索</Button>
          </Form.Item>
          <Form.Item>
            <Button>重置</Button>
          </Form.Item>
        </Form>
        
        <div className="table-operations">
          <Button type="primary" icon={<PlusOutlined />} onClick={() => showEditModal()}>
            新增规则
          </Button>
        </div>
        
        <Table 
          columns={columns} 
          dataSource={rulesData} 
          loading={loading}
          scroll={{ x: 1300 }}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`
          }}
        />
      </Card>
      
      {/* 新增/编辑规则模态框 */}
      <Modal
        title="规则配置"
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={() => form.submit()}
        width={700}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Divider orientation="left">基本信息</Divider>
          <Form.Item name="name" label="规则名称" rules={[{ required: true, message: '请输入规则名称' }]}>
            <Input placeholder="请输入规则名称" />
          </Form.Item>
          
          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item name="field" label="验证字段" rules={[{ required: true, message: '请输入验证字段' }]} style={{ flex: 1 }}>
              <Input placeholder="请输入验证字段" />
            </Form.Item>
            
            <Form.Item name="dataType" label="数据类型" rules={[{ required: true }]} style={{ flex: 1 }}>
              <Select>
                <Option value="字符型">字符型</Option>
                <Option value="数值型">数值型</Option>
                <Option value="日期型">日期型</Option>
                <Option value="日期时间型">日期时间型</Option>
                <Option value="布尔型">布尔型</Option>
              </Select>
            </Form.Item>
          </div>
          
          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item name="ruleType" label="规则类型" rules={[{ required: true }]} style={{ flex: 1 }}>
              <Select>
                <Option value="非空">非空</Option>
                <Option value="正则表达式">正则表达式</Option>
                <Option value="范围">范围</Option>
                <Option value="引用值">引用值</Option>
                <Option value="逻辑">逻辑</Option>
              </Select>
            </Form.Item>
            
            <Form.Item name="target" label="目标数据集" rules={[{ required: true }]} style={{ flex: 1 }}>
              <Select>
                <Option value="患者信息">患者信息</Option>
                <Option value="诊断信息">诊断信息</Option>
                <Option value="医嘱信息">医嘱信息</Option>
                <Option value="检验检查">检验检查</Option>
              </Select>
            </Form.Item>
          </div>
          
          <Form.Item name="condition" label="验证条件" rules={[{ required: true, message: '请输入验证条件' }]}>
            <Input.TextArea placeholder="请输入验证条件" rows={3} />
          </Form.Item>
          
          <Divider orientation="left">配置选项</Divider>
          
          <div style={{ display: 'flex', gap: '16px' }}>
            <Form.Item name="level" label="错误等级" rules={[{ required: true }]} style={{ flex: 1 }}>
              <Radio.Group>
                <Radio value="error">错误</Radio>
                <Radio value="warning">警告</Radio>
              </Radio.Group>
            </Form.Item>
            
            <Form.Item name="status" label="启用状态" valuePropName="checked" style={{ flex: 1 }}>
              <Switch checkedChildren="启用" unCheckedChildren="停用" />
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default ValidationRules; 
